Add two numbers II

Time: O(M+N); Space: O(M+N); medium

You are given two non-empty linked lists representing two non-negative integers.

The most significant digit comes first and each of their nodes contain a single digit.

Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1:

Input: l1 = {ListNode} 7->2->4->3->None, l2 = {ListNode} 5->6->4->None

Output: {ListNode} 7->8->0->7->None

Example 2:

Input: l1 = {ListNode} 1->2->3->None, l2 = {ListNode} 4->5->6->None

Output: {ListNode} 5->7->9->None

Follow up:

  • What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

[10]:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
[11]:
class Solution1(object):
    """
    Time: O(M+N)
    Space: O(M+N)
    """
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        stk1, stk2 = [], []
        while l1:
            stk1.append(l1.val)
            l1 = l1.next
        while l2:
            stk2.append(l2.val)
            l2 = l2.next

        prev, head = None, None
        sum = 0
        while stk1 or stk2:
            sum //= 10
            if stk1:
                sum += stk1.pop()
            if stk2:
                sum += stk2.pop()

            head = ListNode(sum % 10)
            head.next = prev
            prev = head

        if sum >= 10:
            head = ListNode(sum // 10)
            head.next = prev

        return head
[12]:
s = Solution1()

l1 = ListNode(7)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l1.next.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
res = s.addTwoNumbers(l1, l2)
exp = [7,8,0,7]
for val in exp:
    assert res.val == val
    res = res.next

l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(3)
l2 = ListNode(4)
l2.next = ListNode(5)
l2.next.next = ListNode(6)
res = s.addTwoNumbers(l1, l2)
exp = [5,7,9]
for val in exp:
    assert res.val == val
    res = res.next